import json
# from multiprocessing import connection
from apiview.views import View
from django.db import connection
from django.http import HttpResponse
from django.shortcuts import render
import MySQLdb
import datetime

from pymongo import MongoClient
from rest_framework.response import Response
from rest_framework.views import APIView

from workorder.models import *
# Create your views here.


import json
import datetime


class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, datetime.date):
            return obj.strftime("%Y-%m-%d")
        else:
            return json.JSONEncoder.default(self, obj)



def dictfetchall(cursor):

	desc = cursor.description

	return [

	dict(zip([col[0] for col in desc ],row))

	for row in cursor.fetchall()

	]

#构造课程分类层级关系(树)
def get_tree(data):

	lists = []
	tree = {}

	for item in data:
		tree[item['id']] = item

	for i in data:
		if not i['uid']:
			lists.append(tree[i['id']])
		else:
			parent_id = i['uid']
			if "children" not in tree[parent_id]:
				tree[parent_id]["children"] = []
			tree[parent_id]['children'].append(tree[i['id']])

	return lists

#获取课程分类
def get_cate(request):

	#建立查询游标
	cursor = connection.cursor()
	#执行sql
	cursor.execute('SELECT * from cate')
	#获取结果集
	#res = cursor.fetchall()
	res = dictfetchall(cursor)

	#强转
	res = get_tree(res)

	return HttpResponse(json.dumps(res,indent=4,ensure_ascii=False,cls=DateEncoder),content_type='application/json')

from bson import json_util as jsonb
import pymongo
#
# mongo_client = pymongo.MongoClient(host='localhost',port=27017)
#
# db = mongo_client.workflow
#
# table = db.workcate
#
# res = table.find_one({'tid':4})
# print(res)






class GetFields(View):
    def get(self,request):
        mongo_client = pymongo.MongoClient(host='localhost',port=27017)

        db = mongo_client.workflow

        table = db.workcate

        res = table.find({'tid': int(request.Get.get('id',None))})

from ticket.models import *
from ticket.ser import *
from myapp.serializers import *
from myapp.models import *
class AddApproves(APIView):

	def post(self, request):
		obj = ApprovesSer(data=request.data)
		if obj.is_valid():
			obj.save()
			return Response({'msg': '成功', 'code': 1000})
		print(obj.errors)
		return Response({'msg': '失败', 'code': 1001})

	def get(self,request):
		user=Approves.objects.all()
		approves_serializer=ApprovesSer(user,many=True)
		return Response(approves_serializer.data)




class GetCateDetail(APIView):
	def get(self, request):

		uid = request.GET.get('uid')

		client = MongoClient("mongodb://localhost:27017")

		db = client.course

		find = db.formdata.find({'uid':uid})

		print(find)

		return HttpResponse(jsonb.dumps(find, ensure_ascii=False))


















